package com.android.androidbigwork.frames;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.android.androidbigwork.R;
import com.android.androidbigwork.activity.PhotoActivity;
import com.android.androidbigwork.adapter.GridAdapter;
import com.android.androidbigwork.entity.ShareOne;
import com.android.androidbigwork.pojo.LoginUser;
import com.android.androidbigwork.utils.BitmapToFile;
import com.android.androidbigwork.utils.MyCallBack;
import com.android.androidbigwork.utils.RequestUtils;
import com.google.gson.Gson;
import org.xutils.common.Callback;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class Shares extends Fragment implements AdapterView.OnItemClickListener {

    private GridView gridview;
    private GridAdapter adapter;
    private float dp;
    public  static LinkedList<Bitmap> bmp = new LinkedList<>();
    public  static LinkedList<String> drr = new LinkedList<>();
    private LinearLayout ll_popup ;
    private Button button1;// 发布按钮
    public static List<String> urList = new ArrayList<>();
    private View v;
    public static String url ="http://39.108.183.17:8080/sharephotos";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.property_repair,container,false);
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Init();


        verifyStoragePermissions(this);

        final EditText editText1 =  getActivity().findViewById(R.id.editText1);

        button1 = v.findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ShareOne shareOne = new ShareOne();
                shareOne.setMessage(editText1.getText().toString());
                shareOne.setUserId(LoginUser.getAccount());
//                final Gson gson = new Gson();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            LinkedList<File> files=new LinkedList<>();

                                for (String path:urList){
                                    try {
                                        files.add(BitmapToFile.bitmapToFile(path));
                                    }catch (IOException e){
                                        e.printStackTrace();
                                    }
                                }
                                shareOne.setFileList(files);


                            MyCallBack callback = new MyCallBack();

                            RequestUtils.postObj(shareOne,url,callback);

//                            Log.d("分享上传请求", "run: "+callback.getResult());

                        }
                    }).start();


            }
        });
    }

    public void Init() {
        dp = getResources().getDimension(R.dimen.dp);
        gridview = getActivity().findViewById(R.id.Scrollgridview);

        if(gridview==null)
            Log.d("", "Init: griview 为空");

        gridviewInit();
    }


    public void gridviewInit() {

        adapter = new GridAdapter(getContext(),bmp);
        adapter.setFragment(this);
        adapter.setSelectedPosition(0);
        gridview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        gridview.setOnItemClickListener(this);

    }


    public void onPause() {
        super.onPause();
    }



    private class PopupWindows extends PopupWindow {

        private PopupWindows(Context mContext, View parent) {

            View view = View.inflate(mContext, R.layout.item_popupwindows, null);
            ll_popup =  view.findViewById(R.id.ll_popup);
            setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            setHeight(WindowManager.LayoutParams.MATCH_PARENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = view.findViewById(R.id.item_popupwindows_camera);
            Button bt2 =  view.findViewById(R.id.item_popupwindows_Photo);

            Button bt3 =  view.findViewById(R.id.item_popupwindows_cancel);


            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(i, RESULT_LOAD_IMAGE);
                    dismiss();
                }
            });

            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }

    private static final int TAKE_PICTURE = 0;
    private static final int RESULT_LOAD_IMAGE = 1;
    private static final int UI=2;
    private String path = "";
    private Uri mOutPutFileUri;
    String picturePath;



//拍照
    private void photo() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //文件夹
        String path = Environment.getStorageDirectory().toString()+"/elife/img";
        File path1 = new File(path);
        if(!path1.exists()){
            path1.mkdirs();
        }
        File file = new File(path1,System.currentTimeMillis()+".jpg");
        mOutPutFileUri = Uri.fromFile(file);
        picturePath=file.getAbsolutePath();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutPutFileUri);
        startActivityForResult(intent, TAKE_PICTURE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 拍照
            case TAKE_PICTURE:
                if (resultCode==RESULT_OK) {
                    startPhotoZoom(picturePath);
                }

                break;
            // 相册
            case RESULT_LOAD_IMAGE:
                if (resultCode==RESULT_OK) {
                    Uri uri=data.getData();
                    String[] files={MediaStore.Images.Media.DATA};
                    Cursor c=getActivity().getContentResolver().query(uri, files, null, null, null);
                    c.moveToFirst();
                    int ii=c.getColumnIndex(files[0]);
                    path=c.getString(ii);
                    c.close();
                    Log.d("", "点击相册："+path);
                    urList.add(path);
                    startPhotoZoom(path);

                }


                break;

        }
    }

    private Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    private void startPhotoZoom(String uri) {
        drr.add(uri);
        Bitmap bitmap =getLoacalBitmap(drr.get(drr.size()-1 ));
        bmp.add(bitmap);
        gridviewInit();

    }

    public void onDestroy() {
        bmp.clear();
        drr.clear();

        super.onDestroy();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

        if(arg2 == bmp.size()) {
            String sdcardState = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
                if(bmp.size()<10){
                    new PopupWindows(getContext(), gridview);
                }
                else{
                    Toast.makeText(getActivity().getApplicationContext(), "最多只能传9张", Toast.LENGTH_LONG).show();
                }
            }

            else {
                Toast.makeText(getContext().getApplicationContext(), "sdcard已拔出，不能选择照片",	Toast.LENGTH_SHORT).show();
            }
        }

        else
        {
            Intent intent = new Intent(getContext(), PhotoActivity.class);
            intent.putExtra("ID", arg2);
            startActivity(intent);
        }
        try
        {
            ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(arg1.getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        }
        catch(Exception ex)
        {
            Log.e("", ex.toString());
        }


    }
    @Override
    public void onResume()
    {
        adapter.notifyDataSetChanged();
        super.onResume();
    }





    private  final int REQUEST_EXTERNAL_STORAGE = 1;
    private  String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    public  void verifyStoragePermissions(Shares activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity.getContext(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity.getActivity(), PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

}


